package w20rest.java;

import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

public class RestUtil {

    public static RestTemplate createRestTemplate(final Map<String, String> headerAttributes) {
        final SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory() {
            @Override
            public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
                final ClientHttpRequest request = super.createRequest(uri, httpMethod);
                for (Map.Entry<String, String> stringStringEntry : headerAttributes.entrySet()) {
                    request.getHeaders().add(stringStringEntry.getKey(), stringStringEntry.getValue());
                }
                return request;
            }
        };

        return new RestTemplate(simpleClientHttpRequestFactory);
    }

}
